package maps

// map 关键词开头，[]中表示键的类型，[]后面表示值的类型
type Dictionary map[string]string
type DictionaryErr string

const (
	ErrNotFound = DictionaryErr("could not find the word you were looking for")
	ErrWordExits = DictionaryErr("cannot add word because it already exists")
    ErrWordDoesNotExist = DictionaryErr("cannot update word because it does not exist")
)

func (e DictionaryErr) Error() string {
	return string(e)
}

func (d Dictionary)Search(word string) (string,error) {
    definition, ok := d[word]
    if !ok {
        return "", ErrNotFound
    }
    return definition, nil
}

func (d Dictionary)Add(word, definition string) error {
    _, err := d.Search(word)
    switch err {
    case ErrNotFound:
        d[word] = definition
    case nil:
        return ErrWordExits
    default:
        return err
    }
    return nil
}

func (d Dictionary)Update(word, newDefinition string) error {
    _, err := d.Search(word)
    switch err {
    case ErrNotFound:
        return ErrWordDoesNotExist
    case nil:
        d[word] = newDefinition
    default:
        return err
    }
    return nil
}

func (d Dictionary) Delete(word string) {
    delete(d, word)
}